package ext.tianma.part.finishedProduct.util;

import java.rmi.RemoteException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.StringTokenizer;
import java.util.Vector;

import org.apache.log4j.Logger;

import com.ptc.core.lwc.common.view.AttributeDefinitionReadView;
import com.ptc.core.lwc.common.view.TypeDefinitionReadView;
import com.ptc.core.lwc.server.TypeDefinitionServiceHelper;
import com.ptc.core.meta.common.TypeIdentifier;
import com.ptc.core.meta.common.impl.TypeIdentifierUtilityHelper;

import wt.clients.widgets.NumericToolkit;
import wt.fc.WTObject;
import wt.iba.definition.litedefinition.AttributeDefDefaultView;
import wt.iba.definition.litedefinition.BooleanDefView;
import wt.iba.definition.litedefinition.FloatDefView;
import wt.iba.definition.litedefinition.IntegerDefView;
import wt.iba.definition.litedefinition.RatioDefView;
import wt.iba.definition.litedefinition.ReferenceDefView;
import wt.iba.definition.litedefinition.StringDefView;
import wt.iba.definition.litedefinition.TimestampDefView;
import wt.iba.definition.litedefinition.URLDefView;
import wt.iba.definition.litedefinition.UnitDefView;
import wt.iba.value.DefaultAttributeContainer;
import wt.iba.value.IBAHolder;
import wt.iba.value.litevalue.AbstractValueView;
import wt.iba.value.litevalue.BooleanValueDefaultView;
import wt.iba.value.litevalue.FloatValueDefaultView;
import wt.iba.value.litevalue.IntegerValueDefaultView;
import wt.iba.value.litevalue.StringValueDefaultView;
import wt.iba.value.litevalue.TimestampValueDefaultView;
import wt.iba.value.service.IBAValueHelper;
import wt.iba.value.service.StandardIBAValueService;
import wt.log4j.LogR;
import wt.method.RemoteAccess;
import wt.session.SessionHelper;
import wt.util.WTException;
import wt.util.WTPropertyVetoException;
import ext.tianma.bom.util.CSCIBA;

@SuppressWarnings("all")
public class IBAUtil implements RemoteAccess {
	private static final String CLASSNAME = IBAUtil.class.getName();
	private static final Logger log = LogR.getLogger(IBAUtil.class.getName());

	private static Locale LOCALE = Locale.CHINA;
	
	public static List getIBAStringMultiValue(WTObject obj, String ibaName)
			throws WTException {
		List valuelist = new ArrayList();
		String value = "";
		String ibaClass = "wt.iba.definition.StringDefinition";

		try {
			if (obj instanceof IBAHolder) {
				IBAHolder ibaholder = (IBAHolder) obj;
				ibaholder = IBAValueHelper.service.refreshAttributeContainer(
						ibaholder, null, LOCALE, null);
				DefaultAttributeContainer defaultattributecontainer = (DefaultAttributeContainer) ibaholder
						.getAttributeContainer();
				if (defaultattributecontainer != null) {
					List avvlist = getIBAMultiValueView(
							defaultattributecontainer, ibaName, ibaClass);
					if (avvlist != null && avvlist.size() > 0) {
						for (Object object : avvlist) {
							if(object instanceof StringValueDefaultView){
								value = ((StringValueDefaultView) object).getValue();
							}else if(object instanceof IntegerValueDefaultView){
								value = String.valueOf(((IntegerValueDefaultView) object).getValue());
							}else if(object instanceof FloatValueDefaultView){
								value = String.valueOf(((FloatValueDefaultView) object).getValue());
							}
							valuelist.add(value);
						}
					}
				}
			}
		} catch (RemoteException e) {
			e.printStackTrace();
		}
		return valuelist;
	}
	
	public static List getIBAMultiValueView(
			DefaultAttributeContainer dac, String ibaName, String ibaClass)
			throws WTException {
		AbstractValueView aabstractvalueview[] = null;
		AbstractValueView avv = null;
		List list = new ArrayList();
		aabstractvalueview = dac.getAttributeValues();
		for (int j = 0; j < aabstractvalueview.length; j++) {
			String thisIBAName = aabstractvalueview[j].getDefinition()
					.getName();
			String thisIBAClass = (aabstractvalueview[j].getDefinition())
					.getAttributeDefinitionClassName();
			if (thisIBAName.equals(ibaName) ) {
				avv = aabstractvalueview[j];
				list.add(avv);
			}
		}
		return list;
	}
	
	/**
	 * 此方法分类属性和类型属性都可以使用，多值、单值都适用
	 * 
	 * @param obj
	 * @param ibaName
	 * @param newValueList
	 * @param isClassAndSingle 分类属性;"是否单值为ture" 
	 * @throws WTException
	 * @throws RemoteException
	 * @throws WTPropertyVetoException
	 * @throws ParseException
	 */
	public static void setIBAAnyValues(WTObject obj, String ibaName,List<String> newValueList,boolean isClassAndSingle) throws WTException, RemoteException, WTPropertyVetoException, ParseException{
		TypeIdentifier partType = TypeIdentifierUtilityHelper.service.getTypeIdentifier(obj);
		String typename = partType.getTypename();
		String[] typeNameArray = typename.split("\\|");
		ibaName = TypesUtil.getAttrIBAInternalName(typeNameArray[typeNameArray.length -1], ibaName);
		AttributeDefDefaultView attributedefdefaultview = CSCIBA.getAttributeDefinition(ibaName, false);
		
		IBAHolder ibaholder = (IBAHolder)obj;
		
		String ibaClass = "";
		if(attributedefdefaultview instanceof FloatDefView){
			ibaClass = "wt.iba.definition.FloatDefinition";
		}else if(attributedefdefaultview instanceof StringDefView){
			ibaClass = "wt.iba.definition.StringDefinition";
		}else if(attributedefdefaultview instanceof IntegerDefView){
			ibaClass = "wt.iba.definition.IntegerDefinition";
		}else if(attributedefdefaultview instanceof RatioDefView){
			ibaClass = "wt.iba.definition.RatioDefinition";
		}else if(attributedefdefaultview instanceof TimestampDefView){
			ibaClass = "wt.iba.definition.TimestampDefinition";
		}else if(attributedefdefaultview instanceof BooleanDefView){
			ibaClass = "wt.iba.definition.BooleanDefinition";
		}else if(attributedefdefaultview instanceof URLDefView){
			ibaClass = "wt.iba.definition.URLDefinition";
		}else if(attributedefdefaultview instanceof ReferenceDefView){
			ibaClass = "wt.iba.definition.ReferenceDefinition";
		}else if(attributedefdefaultview instanceof UnitDefView){ 
			ibaClass = "wt.iba.definition.UnitDefinition";
		} 

	    // store the new iteration (this will copy forward the obsolete set of IBA values in the database)
		//ibaholder = (IBAHolder)PersistenceHelper.manager.store( (Persistable)ibaholder );

	    // load IBA values from DB (because obsolete IBA values have
	    // been copied forward to new iteration by IBA persistence event handlers)
		ibaholder = IBAValueHelper.service.refreshAttributeContainer(ibaholder, "CSM", null, null);

	    // clear the container to remove all obsolete IBA values and persist this
	    // to remove IBA values from database
	    //*deleteAllIBAValues(ibaholder );
		ibaholder = IBAValueHelper.service.refreshAttributeContainer(ibaholder, null, SessionHelper.manager.getLocale(), null);
		DefaultAttributeContainer defaultattributecontainer = (DefaultAttributeContainer)(ibaholder).getAttributeContainer();
		
		Vector vAbstractvalueview = CSCIBA.getIBAValueViews(defaultattributecontainer,ibaName,ibaClass);
		
		if(null != newValueList && newValueList.size() > 0){
			if(attributedefdefaultview instanceof FloatDefView){
				if(isClassAndSingle){
					String newValue = newValueList.get(0);
					setIBAFloatValue(obj, ibaName,Float.parseFloat(newValue));
				}else{
					setIBAFloatValue(obj, ibaName,newValueList);
				}
				log.info("setIBAFloatValue");
			}else if(attributedefdefaultview instanceof StringDefView){
				if(isClassAndSingle){
					String newValue = newValueList.get(0);
					CSCIBA.setIBAStringValue(obj, ibaName,newValue);
				}else{
					setIBAStringValues(obj, ibaName,newValueList);
				}
				log.info("setIBAStringValue");
			}else if(attributedefdefaultview instanceof IntegerDefView){
				if(isClassAndSingle){
					String newValue = newValueList.get(0);
					CSCIBA.setIBAIntegerValue(obj, ibaName,Integer.parseInt(newValue));
				}else{
					setIBAIntegerValue(obj, ibaName,newValueList);
				}
				log.info("setIBAIntegerValue");
			}else if(attributedefdefaultview instanceof RatioDefView){
				String newValue = newValueList.get(0);
				log.info("setIBARatioValue");
			}else if(attributedefdefaultview instanceof TimestampDefView){
				if(isClassAndSingle){
					String newValue = newValueList.get(0);
					String format = "yyyy-MM-dd HH:mm:ss";
					if (SessionHelper.manager.getLocale().toString().equals("zh_CN")|| SessionHelper.manager.getLocale().toString().equals("zh_TW")) {
						format = "yyyy/MM/dd HH:mm:ss";
					}
					java.text.SimpleDateFormat formats = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					java.text.SimpleDateFormat formatSource = new java.text.SimpleDateFormat(format);
					if (!newValue.contains(":")) newValue = newValue + " 00:00:00";
					CSCIBA.setIBATimestampValue(obj, ibaName,Timestamp.valueOf(formats.format(formatSource.parse(newValue))));
				}else{
					setIBATimestampValue(obj, ibaName,newValueList);
				}
				log.info("setIBATimestampValue");
			}else if(attributedefdefaultview instanceof BooleanDefView){
				if(isClassAndSingle){
					String newValue = newValueList.get(0);
					CSCIBA.setIBABooleanValue(obj, ibaName,Boolean.parseBoolean(newValue));
				}else{
					setIBABooleanValue(obj, ibaName,newValueList);
				}
				log.info("setIBABooleanValue");
			}else if(attributedefdefaultview instanceof URLDefView){
				String newValue = newValueList.get(0);
				//CSCIBA.setIBAURLValue(obj, ibaName,newValue);
				log.info("setIBAURLValue");
			}else if(attributedefdefaultview instanceof ReferenceDefView){
	        	log.info("ReferenceDefView");
			}else if(attributedefdefaultview instanceof UnitDefView){
				String newValue = newValueList.get(0);
			    log.info(newValue);
			    String unit = newValue.substring(newValue.indexOf(" ")+1);
			    newValue = newValue.substring(0, newValue.indexOf(" "));
			    log.info(newValue+" "+unit);
	        	try {
	        		//CSCIBA.setIBAUnitValue(obj, ibaName,Double.parseDouble(newValue), unit);
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
				log.info("setIBAUnitValue");
			}
			
		}
		
		int vabSize = vAbstractvalueview.size();
		if(isClassAndSingle){
			vabSize = vabSize -1;
		}
		for(int i=0; i<vabSize; i++){
			AbstractValueView abstractvalueview = (AbstractValueView) vAbstractvalueview.get(i);
			defaultattributecontainer.deleteAttributeValue(abstractvalueview);
			StandardIBAValueService.theIBAValueDBService.updateAttributeContainer(ibaholder, null, null, null);
			ibaholder = IBAValueHelper.service.refreshAttributeContainer(ibaholder, "CSM", null, null);
		}
	}
	
	public static void setIBAFloatValue(WTObject obj, String ibaName,List<String> newValueList ) throws WTException, RemoteException{
		String ibaClass = "wt.iba.definition.FloatDefinition";
		if(obj instanceof IBAHolder){
			IBAHolder ibaHolder = (IBAHolder)obj;
			for(int i=0; i<newValueList.size(); i++){
				String newValue = newValueList.get(i);
				DefaultAttributeContainer defaultattributecontainer = CSCIBA.getContainer(ibaHolder);
				if(defaultattributecontainer == null){
					defaultattributecontainer = new DefaultAttributeContainer();
					ibaHolder.setAttributeContainer(defaultattributecontainer);
				}
				
				String strFloatValue = String.valueOf(newValue);
				StringTokenizer st = new StringTokenizer(strFloatValue,".");
				int iFloatLength = 0;
				if(st.hasMoreElements()){
					st.nextElement();
					if(st.hasMoreElements()){
						iFloatLength = ((String)st.nextElement()).length();
					}
				}
				if (iFloatLength == 0){
					iFloatLength = -1;
				}else{
					iFloatLength = iFloatLength+ 1;
				}
				int j = NumericToolkit.countSigFigs(newValue);	
				AttributeDefDefaultView attributedefdefaultview = CSCIBA.getAttributeDefinition(ibaName, false);
				FloatValueDefaultView abstractvaluedefaultview1 = new FloatValueDefaultView((FloatDefView)attributedefdefaultview,
						Double.valueOf(newValue).doubleValue(),j);
				defaultattributecontainer.addAttributeValue(abstractvaluedefaultview1);
			
				ibaHolder.setAttributeContainer(defaultattributecontainer);
				StandardIBAValueService.theIBAValueDBService.updateAttributeContainer(ibaHolder, null, null, null);
				ibaHolder = IBAValueHelper.service.refreshAttributeContainer(ibaHolder, "CSM", null, null);
			}
		}
	}
	
	public static void setIBAFloatValue(WTObject obj, String ibaName,float newValue ) throws WTException{
		String ibaClass = "wt.iba.definition.FloatDefinition";
		try{
			if(obj instanceof IBAHolder){
				IBAHolder ibaHolder = (IBAHolder)obj;
				DefaultAttributeContainer defaultattributecontainer = CSCIBA.getContainer(ibaHolder);
				if(defaultattributecontainer == null){
					defaultattributecontainer = new DefaultAttributeContainer();
					ibaHolder.setAttributeContainer(defaultattributecontainer);
				}
				
				String strFloatValue = String.valueOf(newValue);
				
				int j = NumericToolkit.countSigFigs(strFloatValue);	
				
				FloatValueDefaultView abstractvaluedefaultview = (FloatValueDefaultView)CSCIBA.getIBAValueView(defaultattributecontainer, ibaName, ibaClass);
				if(abstractvaluedefaultview != null){
					abstractvaluedefaultview.setValue(Double.valueOf(strFloatValue).doubleValue());
					abstractvaluedefaultview.setPrecision(j);
					defaultattributecontainer.updateAttributeValue(abstractvaluedefaultview);
				}else{
					AttributeDefDefaultView attributedefdefaultview = CSCIBA.getAttributeDefinition(ibaName, false);
					FloatValueDefaultView abstractvaluedefaultview1 = new FloatValueDefaultView((FloatDefView)attributedefdefaultview,
							Double.valueOf(strFloatValue).doubleValue(),j);
					defaultattributecontainer.addAttributeValue(abstractvaluedefaultview1);
				}
				ibaHolder.setAttributeContainer(defaultattributecontainer);
				StandardIBAValueService.theIBAValueDBService.updateAttributeContainer(ibaHolder, null, null, null);
				ibaHolder = IBAValueHelper.service.refreshAttributeContainer(ibaHolder, "CSM", null, null);
			}
		}catch(Exception exception){
			exception.printStackTrace();
		}
	}
	
	public static void setIBAStringValues(WTObject obj, String ibaName, List<String> newValueList) throws WTException, RemoteException{
		String oneNewValue = "";
		if(obj instanceof IBAHolder){
			IBAHolder ibaHolder = (IBAHolder)obj;
			for(int i=0; i<newValueList.size(); i++){
				oneNewValue = newValueList.get(i);
				
				DefaultAttributeContainer defaultattributecontainer = CSCIBA.getContainer(ibaHolder);
				if(defaultattributecontainer == null){
					defaultattributecontainer = new DefaultAttributeContainer();
					ibaHolder.setAttributeContainer(defaultattributecontainer);
				}

				AttributeDefDefaultView attributedefdefaultview = CSCIBA.getAttributeDefinition(ibaName, false);
				StringValueDefaultView abstractvaluedefaultview1 = new StringValueDefaultView((StringDefView)attributedefdefaultview, oneNewValue);
				defaultattributecontainer.addAttributeValue(abstractvaluedefaultview1);

				ibaHolder.setAttributeContainer(defaultattributecontainer);
				StandardIBAValueService.theIBAValueDBService.updateAttributeContainer(ibaHolder, null, null, null);
				ibaHolder = IBAValueHelper.service.refreshAttributeContainer(ibaHolder, "CSM", null, null);
				//wt.iba.value.service.LoadValue.applySoftAttributes(ibaHolder);
			}
		}
		log.info("ENTER..." + ibaName + "..." + newValueList.toString());
	}
	
	public static void setIBAIntegerValue(WTObject obj, String ibaName,List<String> newValueList) throws WTException, RemoteException{
		//String ibaClass = "wt.iba.definition.IntegerDefinition";
		int oneNewValue = 0;
		if(obj instanceof IBAHolder){
			IBAHolder ibaHolder = (IBAHolder)obj;
			for(int i=0; i<newValueList.size(); i++){
				oneNewValue = Integer.parseInt(newValueList.get(i));
				
				DefaultAttributeContainer defaultattributecontainer = CSCIBA.getContainer(ibaHolder);
				if(defaultattributecontainer == null){
					defaultattributecontainer = new DefaultAttributeContainer();
					ibaHolder.setAttributeContainer(defaultattributecontainer);
				}
				
				AttributeDefDefaultView attributedefdefaultview = CSCIBA.getAttributeDefinition(ibaName, false);
				IntegerValueDefaultView abstractvaluedefaultview1 = new IntegerValueDefaultView((IntegerDefView)attributedefdefaultview, oneNewValue);
				defaultattributecontainer.addAttributeValue(abstractvaluedefaultview1);
				
				ibaHolder.setAttributeContainer(defaultattributecontainer);
				StandardIBAValueService.theIBAValueDBService.updateAttributeContainer(ibaHolder, null, null, null);
				ibaHolder = IBAValueHelper.service.refreshAttributeContainer(ibaHolder, "CSM", null, null);
			}
		}
	}
	

	public static void setIBATimestampValue(WTObject obj, String ibaName,List<String> newValueList) throws WTException, RemoteException, ParseException{
		String ibaClass = "wt.iba.definition.TimestampDefinition";
		if(obj instanceof IBAHolder){
			String format = "yyyy-MM-dd HH:mm:ss";
			if (SessionHelper.manager.getLocale().toString().equals("zh_CN")|| SessionHelper.manager.getLocale().toString().equals("zh_TW")) {
				format = "yyyy/MM/dd HH:mm:ss";
			}
			java.text.SimpleDateFormat formats = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			java.text.SimpleDateFormat formatSource = new java.text.SimpleDateFormat(format);
			IBAHolder ibaHolder = (IBAHolder)obj;
			for(int i=0; i<newValueList.size(); i++){
				String newValue = newValueList.get(0);
				if (!newValue.contains(":")) newValue = newValue + " 00:00:00";
				
	          	
				DefaultAttributeContainer defaultattributecontainer = CSCIBA.getContainer(ibaHolder);
				if(defaultattributecontainer == null){
					defaultattributecontainer = new DefaultAttributeContainer();
					ibaHolder.setAttributeContainer(defaultattributecontainer);
				}
				AttributeDefDefaultView attributedefdefaultview = CSCIBA.getAttributeDefinition(ibaName, false);
				TimestampValueDefaultView abstractvaluedefaultview1 = new TimestampValueDefaultView((TimestampDefView)attributedefdefaultview, 
						Timestamp.valueOf(formats.format(formatSource.parse(newValue))));
				defaultattributecontainer.addAttributeValue(abstractvaluedefaultview1);
				
				ibaHolder.setAttributeContainer(defaultattributecontainer);
				StandardIBAValueService.theIBAValueDBService.updateAttributeContainer(ibaHolder, null, null, null);
				ibaHolder = IBAValueHelper.service.refreshAttributeContainer(ibaHolder, "CSM", null, null);
			}
		}
	}
	
	public static void setIBABooleanValue(WTObject obj, String ibaName,List<String> newValueList) throws WTException, RemoteException{
		String ibaClass = "wt.iba.definition.BooleanDefinition";
		if(obj instanceof IBAHolder){
			IBAHolder ibaHolder = (IBAHolder)obj;
			for(int i=0; i<newValueList.size(); i++){
				boolean newValue = Boolean.parseBoolean(newValueList.get(i));
				DefaultAttributeContainer defaultattributecontainer = CSCIBA.getContainer(ibaHolder);
				if(defaultattributecontainer == null){
					defaultattributecontainer = new DefaultAttributeContainer();
					ibaHolder.setAttributeContainer(defaultattributecontainer);
				}
				AttributeDefDefaultView attributedefdefaultview = CSCIBA.getAttributeDefinition(ibaName, false);
				BooleanValueDefaultView abstractvaluedefaultview1 = new BooleanValueDefaultView(
						(BooleanDefView)attributedefdefaultview, newValue);
				defaultattributecontainer.addAttributeValue(abstractvaluedefaultview1);
				
				ibaHolder.setAttributeContainer(defaultattributecontainer);
				StandardIBAValueService.theIBAValueDBService.updateAttributeContainer(ibaHolder, null, null, null);
				ibaHolder = IBAValueHelper.service.refreshAttributeContainer(ibaHolder, "CSM", null, null);
			}
		}
	}
}
